<?php
namespace addons\TfFutures\services;

class OmnicoreService
{
    private $url,$msg;

    private $username,$password;

    public function __construct($url,$username,$password)
    {
        $this->url = $url;
        $this->username = $username;
        $this->password = $password;
        $this->msg = '';
    }

    public function __call($name, $arguments)
    {
        if(!is_scalar($name)){
            throw new Exception(
                'Method name has no scalar value'
            );
        }

        if(is_array($arguments)){
            $params = array_values($arguments);

        }else{
            throw new Exception(
                'params must be given as array'
            );
        }

        $request = array(
            'method'    => $name,
            'params'    => $params,
        );

        $request = json_encode($request);

        $this->msg = $request . PHP_EOL;

        $t = $this->_post(
            $this->url,
            $request,
            array(
                'Content-type: application/json',
                'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password)
            )
        );
        $this->log($this->msg);
        return $t;
    }


    public function _post($url,$param,$header = false){

        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
            curl_setopt($oCurl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');
        }
        if (is_string($param) ) {
            $strPOST = $param;
        } else {
            $strPOST = http_build_query($param);
        }

        if(!empty($header)){
            curl_setopt($oCurl,CURLOPT_HTTPHEADER,$header);
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            $this->msg .= $sContent;
            if(json_decode($sContent)){
                return json_decode($sContent);
            }else{
                return $sContent;
            }
        } else {
            throw new Exception(
                'Api Code %s '. $aStatus['http_code'] . $sContent
            );
        }
    }

    public function log($msg){
        file_put_contents(
            APP_PATH . '/log/' . date('Ymd') . '_rpc.log',
            $msg.PHP_EOL,
            FILE_APPEND
        );
    }
}